package com.ideal.frame.jpa;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.EntityPath;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.Expressions;
import org.springframework.data.domain.Sort;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class DSLRequest {
    protected List<Sort.Order> springOrderByList;
    protected List<BooleanExpression> where;
    protected List<OrderSpecifier<?>> orderByList;

    public DSLRequest() {
        this(new ArrayList(), new ArrayList());
    }

    public DSLRequest(List<BooleanExpression> where) {
        this(where, new ArrayList());
    }

    public DSLRequest(List<BooleanExpression> where, List<OrderSpecifier<?>> orderByList) {
        this.springOrderByList = new ArrayList();
        this.where = where;
        this.orderByList = orderByList;
    }

    public void addOrderBy(OrderSpecifier<?> orderBy) {
        this.orderByList.add(orderBy);
    }

    public void addOrderBy(Sort.Order order) {
        this.springOrderByList.add(order);
    }

    public void addWhere(BooleanExpression whereItem) {
        this.where.add(whereItem);
    }

    public Predicate toPredicate() {
        BooleanBuilder resultWhere = new BooleanBuilder();
        Iterator var2 = this.where.iterator();

        while(var2.hasNext()) {
            BooleanExpression item = (BooleanExpression)var2.next();
            resultWhere.and(item);
        }

        return resultWhere;
    }

    public OrderSpecifier<?>[] toOrderSpecifier(EntityPath<?> root) {
        List<OrderSpecifier<?>> orderSpecifiers = new ArrayList();
        orderSpecifiers.addAll(this.orderByList);
        Iterator var3 = this.springOrderByList.iterator();

        while(var3.hasNext()) {
            Sort.Order order = (Sort.Order)var3.next();
            Expression<Comparable> expression = Expressions.path(Comparable.class, root, order.getProperty());
            OrderSpecifier<?> orderSpecifier = new OrderSpecifier(order.getDirection().equals(Sort.Direction.ASC) ? com.querydsl.core.types.Order.ASC : com.querydsl.core.types.Order.DESC, expression);
            orderSpecifiers.add(orderSpecifier);
        }

        return (OrderSpecifier[])orderSpecifiers.toArray(new OrderSpecifier[0]);
    }
}
